package org.cn.springcloudvv.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.cn.springcloudvv.vo.UserData;

import java.util.Base64;
import java.util.Date;

public class TokenUtils 
{
	private static int expireDays = 10;
	private static String tokenSECRET_ = "beijing2008";
	private static String USERID = "userId";
	private static String APPLICATIONNAME = "applicationName";
	private static String ROLEID = "roleId";

	protected static final Logger logger = LoggerFactory.getLogger(TokenUtils.class);

	public static String buildToken(UserData userData) {
		Date dateExpire = DateUtil.addDays(new Date(),expireDays);//默认10天过期
        // 生成JWT
		String strJWT = Jwts.builder()
                .claim(USERID, userData.getId())
                .claim(ROLEID, userData.getRole())
				.claim(APPLICATIONNAME,userData.getName())
                .setSubject(userData.getPhone())
				.setExpiration(dateExpire)
				.signWith(SignatureAlgorithm.HS512, tokenSECRET_)
				.compact();
		return strJWT;
    }
	
	public static UserData dealToken(String token) {

		// 解析Token
		Claims claims = getTokenClaims(token,tokenSECRET_);
		if(null==claims) {
			return null;
		}
		// 用户名
		Integer userId = Integer.parseInt(claims.get(USERID).toString());
		String name = ""+claims.get(APPLICATIONNAME);
		String phone = claims.getSubject();
		Integer roleId = (Integer)claims.get(ROLEID);
		
		UserData userData = new UserData();
		userData.setId(userId);
		userData.setName(name);
		userData.setPhone(phone);
		userData.setRole(roleId);

		return userData;
	}
	
	public static Claims getTokenClaims(String token,String tokenSECRET_) {
		
		if (StringUtils.isEmpty(token) || token.length()<10)
		{
			logger.info("Error-TokenUtils-getTokenClaims:token="+token);
			return null;
		}
		
		Claims claims = null;
		try {
			claims = Jwts.parser()
					.setSigningKey(tokenSECRET_)
					.parseClaimsJws(token)
					.getBody();
		}catch (Exception e) {
			if (e instanceof ExpiredJwtException)
			{
				logger.info("Error-TokenUtils-ExpiredJwtException:token.length="+token.length());
			}
			else
			{
				logger.info("Error-TokenUtils-getTokenClaims:token.length="+token.length()+",e.getMessage="+e.getMessage());
			}
		}
		return claims;
	}
	
	
	private static String getTokenEncode(String tokenSECRET)
	{
		String key = Base64.getEncoder().encodeToString(tokenSECRET.getBytes());
		return key;
	}

}
